<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
      th:replace="~{layout/base :: layout(~{::title}, ~{::section})}">
<head>
    <title>下载历史 - 电子书下载平台</title>
    <!-- 日期选择器CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
</head>
<body>
    <section>
        <div class="container py-5">
            <div class="row">
                <!-- 页面标题 -->
                <div class="col-12">
                    <h2 class="mb-4">下载历史</h2>
                </div>
                
                <!-- 筛选工具栏 -->
                <div class="col-12 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <form th:action="@{/user/downloads}" method="get" class="row g-3 align-items-end">
                                <div class="col-md-4">
                                    <label for="dateRange" class="form-label">日期范围</label>
                                    <input type="text" class="form-control" id="dateRange" name="dateRange" placeholder="选择日期范围"
                                           th:value="${param.dateRange != null} ? ${param.dateRange} : ''">
                                </div>
                                <div class="col-md-3">
                                    <label for="format" class="form-label">文件格式</label>
                                    <select class="form-select" id="format" name="format">
                                        <option value="">所有格式</option>
                                        <option value="PDF" th:selected="${param.format != null && param.format[0] == 'PDF'}">PDF</option>
                                        <option value="EPUB" th:selected="${param.format != null && param.format[0] == 'EPUB'}">EPUB</option>
                                        <option value="MOBI" th:selected="${param.format != null && param.format[0] == 'MOBI'}">MOBI</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="keyword" class="form-label">关键词</label>
                                    <input type="text" class="form-control" id="keyword" name="keyword" placeholder="书名/作者" 
                                           th:value="${param.keyword != null} ? ${param.keyword} : ''">
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="btn btn-primary w-100">筛选</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                
                <!-- 下载历史列表 -->
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <!-- 批量操作工具栏 -->
                            <div class="d-flex justify-content-between mb-3">
                                <div>
                                    <button type="button" class="btn btn-sm btn-outline-danger" id="batchDeleteBtn" disabled>
                                        <i class="fas fa-trash-alt me-1"></i> 删除选中
                                    </button>
                                </div>
                                <div>
                                    <span class="text-muted">本月已下载: <span th:text="${monthlyDownloads}">23</span>/<span th:text="${dailyDownloadLimit * 30}">300</span></span>
                                    <span class="ms-3 text-muted">今日已下载: <span th:text="${dailyDownloads}">3</span>/<span th:text="${dailyDownloadLimit}">10</span></span>
                                </div>
                            </div>
                            
                            <!-- 下载记录表格 -->
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th width="4%">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="selectAll">
                                                </div>
                                            </th>
                                            <th width="8%">封面</th>
                                            <th width="30%">书籍信息</th>
                                            <th width="12%">格式</th>
                                            <th width="12%">大小</th>
                                            <th width="20%">下载时间</th>
                                            <th width="14%">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- 动态数据 -->
                                        <tr th:each="download : ${downloads}">
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input record-select" type="checkbox" 
                                                           th:value="${download.downloadId}">
                                                </div>
                                            </td>
                                            <td>
                                                <img th:src="${download.coverUrl}" alt="封面" class="img-thumbnail" style="max-height: 50px;">
                                            </td>
                                            <td>
                                                <a th:href="@{'/books/' + ${download.bookId}}" class="fw-bold" th:text="${download.title}">书籍标题</a>
                                                <div class="text-muted small" th:text="${download.author}">作者名</div>
                                            </td>
                                            <td>
                                                <span class="badge bg-secondary" th:text="${download.format}">PDF</span>
                                            </td>
                                            <td th:text="${download.fileSize + ' MB'}">2.5 MB</td>
                                            <td th:text="${#temporals.format(download.downloadTime, 'yyyy-MM-dd HH:mm:ss')}">2023-01-15 12:30:45</td>
                                            <td>
                                                <a th:href="@{'/api/book/download/' + ${download.bookId} + '?format=' + ${download.format}}" 
                                                   class="btn btn-sm btn-outline-primary me-1">
                                                    <i class="fas fa-download"></i>
                                                </a>
                                                <button type="button" class="btn btn-sm btn-outline-danger delete-btn"
                                                        th:data-id="${download.downloadId}">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        
                                        <!-- 静态示例，当没有数据时显示 -->
                                        <tr th:if="${downloads == null || #lists.isEmpty(downloads)}">
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input record-select" type="checkbox" value="1">
                                                </div>
                                            </td>
                                            <td>
                                                <img src="/img/book1.jpg" alt="封面" class="img-thumbnail" style="max-height: 50px;">
                                            </td>
                                            <td>
                                                <a href="/books/1" class="fw-bold">人工智能导论</a>
                                                <div class="text-muted small">李智能</div>
                                            </td>
                                            <td>
                                                <span class="badge bg-secondary">PDF</span>
                                            </td>
                                            <td>15.8 MB</td>
                                            <td>2023-01-15 12:30:45</td>
                                            <td>
                                                <a href="/api/book/download/1?format=PDF" class="btn btn-sm btn-outline-primary me-1">
                                                    <i class="fas fa-download"></i>
                                                </a>
                                                <button type="button" class="btn btn-sm btn-outline-danger delete-btn" data-id="1">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <tr th:if="${downloads == null || #lists.isEmpty(downloads)}">
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input record-select" type="checkbox" value="2">
                                                </div>
                                            </td>
                                            <td>
                                                <img src="/img/book2.jpg" alt="封面" class="img-thumbnail" style="max-height: 50px;">
                                            </td>
                                            <td>
                                                <a href="/books/2" class="fw-bold">Python编程：从入门到实践</a>
                                                <div class="text-muted small">张程序</div>
                                            </td>
                                            <td>
                                                <span class="badge bg-secondary">EPUB</span>
                                            </td>
                                            <td>4.2 MB</td>
                                            <td>2023-01-14 18:45:20</td>
                                            <td>
                                                <a href="/api/book/download/2?format=EPUB" class="btn btn-sm btn-outline-primary me-1">
                                                    <i class="fas fa-download"></i>
                                                </a>
                                                <button type="button" class="btn btn-sm btn-outline-danger delete-btn" data-id="2">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- 分页控件 -->
                            <nav aria-label="Page navigation" th:if="${totalPages > 0}">
                                <ul class="pagination justify-content-center">
                                    <li class="page-item" th:classappend="${currentPage == 1} ? 'disabled' : ''">
                                        <a class="page-link" th:href="@{/user/downloads(page=1, dateRange=${param.dateRange}, format=${param.format}, keyword=${param.keyword})}" aria-label="First">
                                            <span aria-hidden="true">&laquo;&laquo;</span>
                                        </a>
                                    </li>
                                    <li class="page-item" th:classappend="${currentPage == 1} ? 'disabled' : ''">
                                        <a class="page-link" th:href="@{/user/downloads(page=${currentPage - 1}, dateRange=${param.dateRange}, format=${param.format}, keyword=${param.keyword})}" aria-label="Previous">
                                            <span aria-hidden="true">&laquo;</span>
                                        </a>
                                    </li>
                                    <li class="page-item" th:each="i : ${#numbers.sequence(currentPage > 2 ? currentPage - 2 : 1, currentPage + 2 < totalPages ? currentPage + 2 : totalPages)}"
                                        th:classappend="${i == currentPage} ? 'active' : ''">
                                        <a class="page-link" th:href="@{/user/downloads(page=${i}, dateRange=${param.dateRange}, format=${param.format}, keyword=${param.keyword})}" th:text="${i}">1</a>
                                    </li>
                                    <li class="page-item" th:classappend="${currentPage == totalPages} ? 'disabled' : ''">
                                        <a class="page-link" th:href="@{/user/downloads(page=${currentPage + 1}, dateRange=${param.dateRange}, format=${param.format}, keyword=${param.keyword})}" aria-label="Next">
                                            <span aria-hidden="true">&raquo;</span>
                                        </a>
                                    </li>
                                    <li class="page-item" th:classappend="${currentPage == totalPages} ? 'disabled' : ''">
                                        <a class="page-link" th:href="@{/user/downloads(page=${totalPages}, dateRange=${param.dateRange}, format=${param.format}, keyword=${param.keyword})}" aria-label="Last">
                                            <span aria-hidden="true">&raquo;&raquo;</span>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                            
                            <!-- 无数据提示 -->
                            <div class="text-center py-5" th:if="${downloads == null || #lists.isEmpty(downloads)}">
                                <i class="fas fa-download fa-4x text-secondary mb-3"></i>
                                <h5>暂无下载记录</h5>
                                <p class="text-muted">您还没有下载过任何书籍，<a th:href="@{/books/popular}">去看看热门书籍</a></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 确认删除弹窗 -->
        <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        确定要删除所选下载记录吗？此操作不可恢复。
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" id="confirmDelete">确认删除</button>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <!-- 日期选择器JS -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/zh.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化日期选择器
        flatpickr("#dateRange", {
            mode: "range",
            dateFormat: "Y-m-d",
            locale: "zh",
            rangeSeparator: " 至 "
        });
        
        // 全选/取消全选
        const selectAllCheckbox = document.getElementById('selectAll');
        const recordCheckboxes = document.querySelectorAll('.record-select');
        const batchDeleteBtn = document.getElementById('batchDeleteBtn');
        
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', function() {
                recordCheckboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
                updateBatchDeleteButton();
            });
        }
        
        // 单个复选框变化
        recordCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateBatchDeleteButton();
                // 检查是否需要更新全选框状态
                if (!this.checked && selectAllCheckbox.checked) {
                    selectAllCheckbox.checked = false;
                } else if (this.checked) {
                    // 检查是否所有记录都被选中
                    const allChecked = Array.from(recordCheckboxes).every(c => c.checked);
                    selectAllCheckbox.checked = allChecked;
                }
            });
        });
        
        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const selectedCount = Array.from(recordCheckboxes).filter(c => c.checked).length;
            batchDeleteBtn.disabled = selectedCount === 0;
            batchDeleteBtn.textContent = selectedCount > 0 ? `删除选中 (${selectedCount})` : '删除选中';
        }
        
        // 单条删除
        const deleteButtons = document.querySelectorAll('.delete-btn');
        const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
        const confirmDeleteBtn = document.getElementById('confirmDelete');
        let currentDeleteId = null;
        let isBatchDelete = false;
        
        deleteButtons.forEach(button => {
            button.addEventListener('click', function() {
                currentDeleteId = this.getAttribute('data-id');
                isBatchDelete = false;
                deleteModal.show();
            });
        });
        
        // 批量删除
        if (batchDeleteBtn) {
            batchDeleteBtn.addEventListener('click', function() {
                const selectedIds = Array.from(recordCheckboxes)
                    .filter(c => c.checked)
                    .map(c => c.value);
                
                if (selectedIds.length > 0) {
                    isBatchDelete = true;
                    currentDeleteId = selectedIds;
                    deleteModal.show();
                }
            });
        }
        
        // 确认删除
        if (confirmDeleteBtn) {
            confirmDeleteBtn.addEventListener('click', function() {
                if (isBatchDelete) {
                    // 批量删除
                    fetch('/api/download/delete-batch', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ ids: currentDeleteId })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            window.location.reload();
                        } else {
                            showToast('删除失败: ' + data.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast('删除失败，请重试', 'error');
                    })
                    .finally(() => {
                        deleteModal.hide();
                    });
                } else {
                    // 单条删除
                    fetch(`/api/download/delete/${currentDeleteId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            // 删除成功，刷新页面
                            window.location.reload();
                        } else {
                            showToast('删除失败: ' + data.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast('删除失败，请重试', 'error');
                    })
                    .finally(() => {
                        deleteModal.hide();
                    });
                }
            });
        }
    });
    </script>
</body>
</html> 